import Vue from 'vue'
import Vuex from 'vuex'
import {
  getSearchShop
} from '../api/search'
import {
  getUserInfo,
  getLogout
} from '../api/login'
import {
  RECEIVE_SEARCH_SHOPS,
  RECEIVE_USER_INFO,
  RESET_USER_INFO
} from './mutation-type'

Vue.use(Vuex)
const savePlugin = store => {
  // 添加对每次 mutation 调用后执行的任务的监听
  store.subscribe((mutations, state) => {
    // 将购物车商品保存到 localStorage 中（JSON.stringify()序列化）
    localStorage.setItem('cart', JSON.stringify(state.cart))
  })
}

export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production', // 在开发环境下开启严格模式，生产环境下关闭
  plugins: [savePlugin],
  state: {
    cart: JSON.parse(localStorage.getItem('cart')) || [],
    latitude: 40.10038, // 纬度
    longitude: 116.36867, // 经度
    searchShops: [], // 搜索得到的商家列表
    userInfo: {}
  },
  getters: {
    // 全选
    isAllChecked (state) {
      return state.cart.every(item => item.isChecked)
    },

    // 计算总价
    totalMoney (state) {
      return Math.floor(state.cart.reduce((sum, item) => {
        if (item.isChecked) {
          sum += item.price * item.amount
        }
        return sum
      }, 0) * 100)
    }
  },
  mutations: {
    // 搜索店铺数据
    [RECEIVE_SEARCH_SHOPS] (state, { searchShops }) {
      state.searchShops = searchShops
    },
    // 存储用户数据
    [RECEIVE_USER_INFO] (state, { userInfo }) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    // 用户退出
    [RESET_USER_INFO] (state) {
      state.userInfo = {}
    },
    // 添加至购物车
    addToCart (state, playload) {
      const flag = state.cart.some(item => item.name === playload.name)
      if (flag) {
        state.cart = state.cart.map(prod => {
          const copy = { ...prod }
          if (copy.name === playload.name) {
            copy.amount += playload.amount
          }
          return copy
        })
      } else {
        state.cart.push({
          ...playload,
          isChecked: true
        })
      }
    },
    // 删除商品
    removeFromCart (state, name) {
      state.cart = state.cart.filter(item => item.name !== name)
    },

    // 修改数量
    changeAmount (state, { name, amount }) {
      state.cart = state.cart.map(item => {
        const copy = { ...item }
        if (item.name === name) {
          copy.amount = amount
        }
        return copy
      })
    },

    // 切换选中状态
    toggleChecked (state, name) {
      state.cart = state.cart.map(item => {
        const copy = { ...item }
        if (item.name === name) {
          copy.isChecked = !copy.isChecked
        }
        return copy
      })
    },

    // 切换全选状态
    toggleCheckedAll (state, preChecked) {
      state.cart = state.cart.map(item => {
        const copy = { ...item }
        copy.isChecked = !preChecked
        return copy
      })
    },
    // 搜索店铺数据
    [RECEIVE_SEARCH_SHOPS] (state, { searchShops }) {
      state.searchShops = searchShops
    },
    // 存储用户数据
    [RECEIVE_USER_INFO] (state, { userInfo }) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    // 用户退出
    [RESET_USER_INFO] (state) {
      state.userInfo = {}
    }
  },
  actions: {
    async searchShops ({ commit, state }, keyword) {
      const geohash = state.latitude + ',' + state.longitude
      const result = await getSearchShop(geohash, keyword)
      if (result.code === 0) {
        const searchShops = result.data
        commit(RECEIVE_SEARCH_SHOPS, { searchShops })
      }
    },
    recordUser ({ commit }, userInfo) {
      commit(RECEIVE_USER_INFO, { userInfo })
    },
    async getUserInfo ({ commit }) {
      const result = await getUserInfo()
      if (result.code === 0) {
        const userInfo = result.data
        commit(RECEIVE_USER_INFO, { userInfo })
      }
    },
    // 异步登出
    async logout ({ commit }) {
      const result = await getLogout()
      if (result.code === 0) {
        commit(RESET_USER_INFO)
      }
    }
  },
  modules: {
  }
})
